package com.aiyige.page.home;


import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.aiyige.R;
import com.aiyige.base.BaseFragment;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.eventbus.EventRefreshHomePageBanner;
import com.aiyige.base.eventbus.EventSelectInterest;
import com.aiyige.base.eventbus.EventSelectRegion;
import com.aiyige.base.eventbus.EventTapBottomItemRefresh;
import com.aiyige.model.Page;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.home.adapter.HomeAdapter;
import com.aiyige.page.interest.model.Interest;
import com.aiyige.page.webview.util.PreloadUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.fastjson.JSON;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;

public class HomeDataPage extends BaseFragment implements CommonDataView.RetrofitStub, HomeDataPageInterface {
    private Interest interest;
    private int sortWeight;
    private int position;
    @BindView(R.id.cdv)
    CommonDataView cdv;
    Unbinder unbinder;
    HomeAdapter homeAdapter;
    Handler mainHandler;


    public HomeDataPage() {

    }

    @Override
    public int getPosition() {
        return position;
    }

    @Override
    public void setPosition(int position) {
        this.position = position;
    }

    @Override
    public Interest getInterest() {
        return interest;
    }

    @Override
    public int getSortWeight() {
        return sortWeight;
    }

    @Override
    public void setSortWeight(int sortWeight) {
        this.sortWeight = sortWeight;
    }

    @Override
    public void setInterest(Interest interest) {
        this.interest = interest;
    }

    @Override
    public String getPageTitle() {
        switch (interest.getCategory()) {
            case Interest.CATEGORY_RECOMMEND:
                return StringUtils.getString(R.string.recommend);
            case Interest.CATEGORY_HOT:
                return StringUtils.getString(R.string.hot);
            case Interest.CATEGORY_FOLLOW:
                return StringUtils.getString(R.string.follow);
            case Interest.CATEGORY_INDUSTRY:
            case Interest.CATEGORY_INTEREST:
                return interest.getTitle();
            default:
                return "";
        }
    }

    public static HomeDataPage newInstance(Interest interest, int sortWeight, int position) {
        HomeDataPage fragment = new HomeDataPage();
        fragment.setAutoRegisterEventBus(true);
        fragment.setInterest(interest);
        fragment.setSortWeight(sortWeight);
        fragment.setPosition(position);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_home_data, container, false);
        unbinder = ButterKnife.bind(this, view);
        homeAdapter = new HomeAdapter();
        mainHandler = new Handler(Looper.getMainLooper());
        cdv.config(homeAdapter, this);
        cdv.setActionCallback(new CommonDataView.UserActionCallback() {
            @Override
            public void onUserRefresh() {
                EventBus.getDefault().post(new EventRefreshHomePageBanner());
            }

            @Override
            public void onUserLoadMore() {

            }
        });
        cdv.setErrorHandler(new CommonDataView.ErrorHandler() {
            @Override
            public void onResponseError(String errorMsg) {
                EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                        .itemType(EventTapBottomItemRefresh.ITEM_TYPE_HOME)
                        .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_FAILED)
                        .build());
            }

            @Override
            public void onNetError(String errorMsg) {
                EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                        .itemType(EventTapBottomItemRefresh.ITEM_TYPE_HOME)
                        .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_FAILED)
                        .build());
            }
        });
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initData() {
        cdv.doRefreshRequest();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventSelectRegion(EventSelectRegion event) {
        //cdv.doRefreshRequest();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventSelectInterest(EventSelectInterest event) {
   //     cdv.doRefreshRequest();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventTapBottomItemRefresh event) {
        if (isFragmentVisible()
                && event.getItemType() == EventTapBottomItemRefresh.ITEM_TYPE_HOME
                && event.getActionType() == EventTapBottomItemRefresh.ACTION_TYPE_START_REFRESH
                && event.getInterest().equals(interest)) {
            cdv.backToTop(false);
            cdv.showRefreshing();
            mainHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    cdv.doRefreshRequest();
                }
            }, 1000);
        }
    }


    @Override
    public Call<ResponseBody> call(long currentPage) {
        if (interest == null) {
            return null;
        }
        String column = "";
        switch (interest.getCategory()) {
            case Interest.CATEGORY_FOLLOW:
                column = Moment.MOMENT_LIST_TYPE_ATTENTION;
                break;
            case Interest.CATEGORY_HOT:
                column = Moment.MOMENT_LIST_TYPE_HEATEST;
                break;
            case Interest.CATEGORY_RECOMMEND:
                column = Moment.MOMENT_LIST_TYPE_RECOMMEND;
                break;

            case Interest.CATEGORY_INTEREST:
            case Interest.CATEGORY_INDUSTRY:
                column = interest.getId();
                break;
        }
        return ApiManager.getService().recommendMommentList(column, currentPage, 15);
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Moment> momentList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                momentList.addAll(JSON.parseArray(page.getContent(), Moment.class));
            }
            for (Moment moment : momentList) {
                Moment safeMoment = new Moment(moment);
                resultList.add(safeMoment);
                PreloadUtil.preloadH5Moment(safeMoment);
            }
            EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                    .itemType(EventTapBottomItemRefresh.ITEM_TYPE_HOME)
                    .actionType(EventTapBottomItemRefresh.ACTION_TYPE_REFRESH_SUCCEED)
                    .build());
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }

    }

}
